package com.hbx.controller;


import com.hbx.aspect.annotation.SensitiveFilter;
import com.hbx.constant.ResponseStateConstant;
import com.hbx.constant.TableEnum;
import com.hbx.logs.annotation.MarkLog;
import com.hbx.logs.OperaTypeEnum;
import com.hbx.dto.user.CheckPwdDto;
import com.hbx.dto.user.UpdatePwdDto;
import com.hbx.dto.user.UpdateUserDto;
import com.hbx.dto.user.UserAuthDto;
import com.hbx.dto.user.UserInsertDto;
import com.hbx.dto.user.UserRankDto;
import com.hbx.dto.user.UserRegisterDto;
import com.hbx.dto.user.UserSearchDto;
import com.hbx.exception.RspException;
import com.hbx.service.RoleUserService;
import com.hbx.service.UserService;
import com.hbx.utils.Result;
import com.hbx.vo.SearchUserVo;
import com.hbx.vo.UserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hbx
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户处理器")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleUserService roleUserService;

    /**
     * 检查用户名是否存在
     *
     * @param username
     * @return
     */
    @GetMapping("/checkUsernameExist")
    @ApiOperation("检查用户名是否存在")
    public Result checkUsernameExist(@RequestParam("username") @ApiParam(value = "用户名", required = true) String username) {
        if (!StringUtils.hasLength(username)) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "用户名为必传项");
        }
        return userService.checkUsernameExist(username);
    }

    /**
     * 检查邮箱是否存在
     * @param email
     * @return
     */
    @RequestMapping(value = "/checkEmailExist",method = RequestMethod.GET)
    @ApiOperation("检查邮箱是否存在")
    public Result checkEmailExist(@RequestParam("email") @ApiParam(value = "邮箱", required = true) String email) {
        if (!StringUtils.hasLength(email)) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "邮箱为必传项");
        }
        return userService.checkEmailExist(email);
    }

    /**
     * 用户注册
     *
     * @param user
     * @param result
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ApiOperation(value = "用户注册")
    @SensitiveFilter
    public Result userRegister(
            @RequestBody @ApiParam(value = "注册主体", required = true) @Valid UserRegisterDto user, BindingResult result) {
        if (result.hasErrors()) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, result.getFieldError().getDefaultMessage());
        }
        return userService.register(user);
    }

    /**
     * 激活用户
     *
     * @param code
     * @return
     */
    @ApiOperation("激活用户")
    @RequestMapping(value = "/active/{code}", method = RequestMethod.GET)
    public Result active(@PathVariable("code") @ApiParam(value = "激活码") String code) {
        return userService.activeUser(code);
    }

    /**
     * 条件查询所有用户
     * @param userSearch
     * @param result
     * @return
     */
    @ApiOperation("查询所有用户")
    @RequestMapping(value = "/userlist",method = RequestMethod.POST)
    public Result<SearchUserVo> userList(@RequestBody @Valid @ApiParam(value = "用户搜索过滤", required = true) UserSearchDto userSearch, BindingResult result) {
        if (result.hasErrors()) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, result.getFieldError().getDefaultMessage());
        }
        return userService.pageListByQuery(userSearch);
    }

    /**
     * 后台添加用户
     * @param userdto
     * @return
     */
    @RequestMapping(value = "/admin/insert",method = RequestMethod.POST)
    @ApiOperation("后台添加用户")
    @SensitiveFilter
    public Result insert(@RequestBody @ApiParam(value = "用户操作对象",required = true) @Valid UserInsertDto userdto,BindingResult result){
        if (result.hasErrors()){
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR,result.getFieldError().getDefaultMessage());
        }
        if (!StringUtils.hasLength(userdto.getEmail())) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "邮箱地址为必填项");
        }

        if (ObjectUtils.isEmpty(userdto.getType())) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "身份为必填项");
        }

        return userService.add(userdto);
    }

    /**
     * 后台修改用户
     * @param userdto
     * @return
     */
    @RequestMapping(value = "/admin/update",method = RequestMethod.POST)
    @ApiOperation("后台修改用户状态")
    public Result update(@RequestBody @ApiParam(value = "用户操作对象",required = true) @Valid UserInsertDto userdto,BindingResult result){
        if (result.hasErrors()){
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR,result.getFieldError().getDefaultMessage());
        }
        if (ObjectUtils.isEmpty(userdto.getUserId())) {
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "用户id为必填项");
        }

        return userService.update(userdto);
    }

    /**
     * 充值用户密码
     * @param userId
     * @return
     */
    @RequestMapping(value = "/resetPwd/{userId}",method = RequestMethod.GET)
    @ApiOperation("重置用户密码")
    public Result resetPwd(@PathVariable("userId") @ApiParam(value = "用户id",required = true) Integer userId){
        return userService.resetPwd(userId);
    }

    /**
     * 获得我的详细信息
     * @return
     */
    @RequestMapping(value = "/getMyInfo",method = RequestMethod.GET)
    @ApiOperation("获得我的详细信息")
    public Result<UserInfoVo> getMyInfo(){
        Result<UserInfoVo> r = new Result<>();
        userService.getMyInfo(r);
        return r;
    }

    /**
     * 获得用户详细信息
     * @return
     */
    @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    @ApiOperation("获得用户详细信息")
    public Result<UserInfoVo> getUserInfo(@RequestParam("userId") Integer userId){
        Result<UserInfoVo> r = new Result<>();
        if (userId == null){
            r.setCode(400).setMsg("userId为必传项");
            return r;
        }
        userService.getUserInfo(userId, r);
        return r;
    }

    /**
     * 用户修改头像
     * @param file
     * @return
     */
    @RequestMapping(value = "/updateAvator",method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    public Result updateAvator(@RequestParam("file") @ApiParam(value = "文件",required = true) MultipartFile file){
        Result r = new Result();
        try {
            userService.updateAvator(file,r);
        } catch (Exception e) {
            r.setCode(ResponseStateConstant.OPERA_FAIL).setMsg("图片上传失败");
        }
        return r;
    }

    /**
     * 更新用户信息
     * @param updateUserDto
     * @return
     */
    @RequestMapping(value = "/updateInfo",method = RequestMethod.POST)
    @ApiOperation("用户修改信息")
    @SensitiveFilter
    public Result updateInfo(@RequestBody @Valid UpdateUserDto updateUserDto,BindingResult result){
        if (result.hasErrors()){
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR,result.getFieldError().getDefaultMessage());
        }
        Result r = new Result();
        userService.updateInfo(updateUserDto,r);
        return r;
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/deleteUser",method = RequestMethod.GET)
    @ApiOperation("删除用户信息")
    public Result updateInfo(@RequestParam("userId") Integer userId){
        if (ObjectUtils.isEmpty(userId)){
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, "用户id不能为空");
        }
        Result r = new Result();
        userService.deleteUser(userId, r);
        return r;
    }

    /**
     * 获得用户的已有权限
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getUserHasRoleId",method = RequestMethod.GET)
    @ApiOperation("获得用户的已有权限")
    public Result getUserHasRoleId(@RequestParam("userId") Integer userId){
        Result r = new Result();
        if (ObjectUtils.isEmpty(userId)){
            r.setCode(ResponseStateConstant.PARAMETER_ERROR).setMsg("userId为必传项");
            return r;
        }
        roleUserService.getUserHasRoleId(userId, r);
        return r;
    }

    /**
     * 给用户授权
     * @param userAuthDto
     * @param result
     * @return
     */
    @RequestMapping(value = "/saveRoleToUser",method = RequestMethod.POST)
    @ApiOperation("给用户授权")
    public Result saveRoleToUser(@RequestBody @Valid UserAuthDto userAuthDto, BindingResult result){
        if (result.hasErrors()){
            throw new RspException(ResponseStateConstant.PARAMETER_ERROR, result.getFieldError().getDefaultMessage());
        }
        Result r = new Result();
        userService.saveRoleToUser(userAuthDto, r);
        return r;
    }

    /**
     * 检查旧密码是否正确
     * @param dto
     * @param result
     * @return
     */
    @RequestMapping(value = "/checkOldPassword",method = RequestMethod.POST)
    @ApiOperation("检查旧密码是否正确")
    public Result checkOldPassword(@RequestBody @Valid CheckPwdDto dto, BindingResult result){
        Result r = new Result();
        if (result.hasErrors()){
            r.setCode(400).setMsg(result.getFieldError().getDefaultMessage());
            return r;
        }
        userService.checkOldPassword(dto, r);
        return r;
    }

    /**
     * 修改密码
     * @param dto
     * @param result
     * @return
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    @ApiOperation("修改密码")
    public Result updatePassword(@RequestBody @Valid UpdatePwdDto dto, BindingResult result){
        Result r = new Result();
        if (result.hasErrors()){
            r.setCode(400).setMsg(result.getFieldError().getDefaultMessage());
            return r;
        }
        userService.updatePassword(dto, r);
        return r;
    }

    /**
     * 给用户授衔
     * @param dto
     * @param result
     * @return
     */
    @RequestMapping(value = "/saveRankToUser", method = RequestMethod.POST)
    @ApiOperation("给用户授衔")
    @MarkLog(operate = OperaTypeEnum.UPDATE,  tables = TableEnum.USER_RANK, desc = "给用户授衔")
    public Result saveRankToUser(@RequestBody UserRankDto dto, BindingResult result){
        if(result.hasErrors()){
            return Result.error().setCode(400).setMsg(result.getFieldError().getDefaultMessage());
        }
        Result r = new Result();
        userService.saveRankToUser(dto, r);
        return r;
    }

    /**
     * 获得用户已有头衔
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getUserHasRankId", method = RequestMethod.GET)
    @ApiOperation("获得用户已有头衔id")
    public Result getUserHasRankId(@RequestParam("userId") Integer userId){
        if(userId == null){
            return Result.error().setCode(400).setMsg("userId为必传项");
        }
        Result r = new Result();
        userService.getUserHasRankId(userId, r);
        return r;
    }
}

